package com.hks360.car_treasure.util;


import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by rwq on 2016/4/14.
 */

/**
 *功能1：从Json字符串解析到JavaBean
 *功能2：从JsonArray字符串数组解析到JavaBean集合
 *
 * **/
public class GsonUtil {

    //从Json字符串解析到JavaBean
    public static  <T> T parseJson(String jsonString,Class<T> clazz) {
        if (isEmptyJsonStr(jsonString)) {
            return null;
        }
        Gson gson = new Gson();
        try {
            return gson.fromJson(jsonString, clazz);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //Javabean到Json字符串
    public static <T> String toJson(T t) {
        Gson gson = new Gson();
        return gson.toJson(t);
    }
    //Javabean到Json数组字符串
    public static <T> String toJson(List<T> t,Type type) {
        Gson gson = new Gson();
        return gson.toJson(t,type);
    }

    //从JsonArray字符串数组解析到JavaBean
    public static <T> List<T> parseJsonArray(String jsonString,Type type) {
        if (isEmptyJsonStr(jsonString)) {
            return null;
        }
        Gson gson = new Gson();
        try {
            List<T> list = gson.fromJson(jsonString,type);
            return list;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //Json的判空工具
    private static boolean isEmptyJsonStr(String jsonString) {
        if (jsonString == null) {
            return true;
        }
        switch (jsonString) {
            case "":
            case "null":
            case "{}":
                return true;
        }
        return false;
    }


}
